<template>
	<view class="goods-content">
		<u-navbar :title="title" :autoBack="true" bgColor="#9dae8a" placeholder></u-navbar>
		<!-- <ycy-top-bar>{{ title }}</ycy-top-bar> -->
		<u-toast ref="uToast"></u-toast>
		<view class="form-content" v-if="JSON.stringify(currentItem) != '{}'">
			<u--form :borderBottom="false" :model="currentItem" labelWidth="80" ref="uForm">
				<u-form-item label="商品分类" prop="typeName">
					<view v-if="!isEdit">{{ currentItem.typeName }}</view>
					<u--input v-else v-model="currentItem.typeName" border="bottom" readonly placeholder="请选择商品分类" @click.native="onOpenPicker"></u--input>
					<u-picker :show="isShowTypePicker" :columns="typePickerList" keyName="name" @confirm="onTypeConfirm" @cancel="isShowTypePicker=false"></u-picker>
				</u-form-item>
				<u-form-item label="商品名称" prop="name">
					<view v-if="!isEdit">{{ currentItem.name }}</view>
					<u--input v-else v-model="currentItem.name" border="bottom" clearable placeholder="请输入商品名称"></u--input>
				</u-form-item>
				<u-form-item label="商品价格" prop="price">
					<view v-if="!isEdit">￥{{ currentItem.price }}</view>
					<u--input v-else v-model="currentItem.price" prefixIcon="rmb" border="bottom" clearable placeholder="请输入商品价格"></u--input>
				</u-form-item>
				<u-form-item label="商品尺码" prop="size">
					<view class="tag-box">
						<view class="tag-item" v-for="(item, index) in sizeList" :key="index">
							<u-tag :disabled="isEdit" :text="item.label" :plain="!item.checked" type="error" :name="index" @click="checkboxClick(index)"></u-tag>
						</view>
					</view>
				</u-form-item>
				<u-form-item label="商品图片" prop="size">
					<u-upload v-if="isEdit" :fileList="fileList" @afterRead="afterReadPic" @delete="deletePic" :maxCount="1" :previewFullImage="true"></u-upload>
					<image v-else class="goods-image" @click.stop="onPreviewImg" :src="currentItem.url ? currentItem.url : '/static/image/defaultImg.png'"></image>
				</u-form-item>
				<!-- 尺码卡片 -->
				<view class="size-card" v-for="(params, index) in currentItem.paramsList" :key="index">
					<view class="size-card-title">尺码{{ params.size }}</view>
					<view v-if="isEdit" class="add-btn"><u-icon name="plus" size="24" @click="onAddColor(index)"></u-icon></view>
					<!-- 新增的时候会出现数据更新了，但界面不更新得情况。原因是unapp的bug,解决办法是使用v-if强制更新。 -->
					<view class="color-table" v-if="isRefresh">
						<view class="color-table-item" v-for="(colorItem, i) in params.colorCountList" :key="i">
							<view class="color-table-item-box">
								<view class="color-table-item-box-title">颜色</view>
								<view class="color-table-item-box-content" :style="isEdit ? 'width: 160rpx;' : ''">
									<u-tag v-if="!isEdit" :text="colorItem.color" plain type="error"></u-tag>
									<u--input v-else v-model="colorItem.color" clearable placeholder=" "></u--input>
								</view>
							</view>
							<view class="color-table-item-box">
								<view class="color-table-item-box-title">数量</view>
								<view class="color-table-item-box-content" v-if="!isEdit" style="width: 80rpx;font-weight: bold;">{{ colorItem.count }}</view>
								<view class="color-table-item-box-content" v-else><u-number-box v-model="colorItem.count" integer :min="0"></u-number-box></view>
							</view>
							<view class="color-table-item-box" v-if="isEdit">
								<view class="color-table-item-box-content"><button class="delete-btn" @click="onRemoveColor(index,i)">删除</button></view>
							</view>
						</view>
					</view>
				</view>
			</u--form>
		</view>
		<view class="save-btn" v-if="title != '查看商品信息'">
			<u-button text="保 存" icon="checkmark" color="#9dae8a" iconColor="#fff" @click="onSave"></u-button>
		</view>
	</view>
</template>

<script>
	export default {
		onLoad(options) {
			if(options.type == 'add') this.initAddPage(options);
			if(options.type == 'check') this.initCheckPage(options);
			if(options.type == 'edit') this.initEditPage(options);
		},
		data() {
			return {
				// currentId: '',
				isEdit: false,
				isRefresh: true,
				isShowTypePicker: false,
				title: '',
				fileList: [],
				currentItem: {},
				typePickerList: [[]], //需要是二维数组
				sizeList: [],
				defaultSizeList: [],
				backupsParamsList:[]
			};
		},
		methods: {
			initAddPage(options) {
				this.title = `新增${ options.typeName }商品信息`;
				this.isEdit = true;
				this.getGoodsTypeList();
				this.getDefaultSizeList();
				this.getEditSizeList();
				this.fileList = [];
				this.currentItem.typeId = options.typeId;
				this.currentItem.typeName = options.typeName;
				this.currentItem.paramsList = [];
			},
			async initCheckPage(options) {
				this.title = '查看商品信息'
				this.isEdit = false;
				await this.getGoodsDetail(options.goodsId);
				this.initGoodsImage(this.currentItem.url);
				this.getCheckSizeList();
			},
			async initEditPage(options) {
				this.title = '修改商品信息'
				this.isEdit = true;
				this.getGoodsTypeList();
				await this.getGoodsDetail(options.goodsId);
				this.initGoodsImage(this.currentItem.url);
				this.getDefaultSizeList();
				this.getEditSizeList();
			},
			async deletePic(event) {
				const res = await this.$utils.removeImg(this.currentItem.url);
				if(res.code == 200) {
					this.fileList.splice(event.index, 1);
					this.currentItem.url = '';
				}else this.$toast.error(this,res.message);
			},
			async afterReadPic(event) {
				// console.log('afterReadPic event',event)
				const res = await this.$utils.uploadImg(event.file.url);
				if(res.code == 200) {
					this.initGoodsImage(event.file.url);
					this.currentItem.url = res.data.url;
				}else this.$toast.error(this,res.message);
				console.log('afterReadPic',res)
			},
			onPreviewImg() {
				uni.previewImage({
					urls: this.currentItem.url ? [this.currentItem.url] : ['/static/image/defaultAvatar.png']
				})
			},
			onOpenPicker() {
				this.isShowTypePicker = true;
			},
			onTypeConfirm(item) {
				// console.log(item)
				//item中包括 indexs,value,values 其中indexs是下标数组,value是对应值的数组,values是所有选项值的数组。
				this.currentItem.typeId = item.value[0].id;
				this.currentItem.typeName = item.value[0].name;
				if(this.title != '修改商品信息') this.title = `新增${ item.value[0].name }商品信息`;
				this.isShowTypePicker = false;
			},
			checkboxClick(index) {
				this.sizeList[index].checked = !this.sizeList[index].checked;
				const item = this.sizeList[index];
				if(item.checked) this.currentItem.paramsList.push({ size: item.label, colorCountList: [{ color: '编辑颜色',count: 1 }] })
				else this.currentItem.paramsList.splice(this.getIndexInParamsList(index),1);
			},
			onAddColor(paramsListIndex){
				this.currentItem.paramsList[paramsListIndex].colorCountList.push({ color: `编辑颜色`,count: 1 });
				this.refreshColorList();  //新增的时候会出现数据更新了，但界面不更新得情况。原因是unapp的bug,解决办法是使用v-if强制更新。
			},
			onRemoveColor(paramsListIndex, colorListIndex) {
				this.currentItem.paramsList[paramsListIndex].colorCountList.splice(colorListIndex,1);
				this.refreshColorList();  //新增的时候会出现数据更新了，但界面不更新得情况。原因是unapp的bug,解决办法是使用v-if强制更新。
			},
			async getGoodsTypeList() {
				const res = await this.$api.goodsType.findAll('');
				if(res.code == 200) this.typePickerList = [res.data];
				else this.$toast.error(this,res.message);
			},
			async getGoodsDetail(goodsId) {
				const res = await this.$api.goodsManage.findOneDetail(goodsId);
				if(res.code == 200) this.currentItem = res.data;  
				else this.$toast.error(this,res.message);
			},
			getDefaultSizeList() {
				this.defaultSizeList = ['XS','S','M','L','XL','2XL','3XL'];
			},
			getEditSizeList() {
				this.sizeList = this.defaultSizeList.map(defaultItem => {
					let isChecked = false;
					if(this.currentItem.paramsList) {
						for (let item of this.currentItem.paramsList) {
							if(defaultItem == item.size) {
								isChecked = true;
								break;
							}
						}
					}
					if(isChecked) return { label: defaultItem, checked: true };
					else return { label: defaultItem, checked: false };
				})
			},
			getCheckSizeList() {
				this.sizeList = this.currentItem.paramsList.map(item => {
					return { label: item.size, checked: true };
				})
			},
			getIndexInParamsList(index) {
				for (const i in this.currentItem.paramsList) {
					const item = this.currentItem.paramsList[i];
					if(item.size == this.sizeList[index].label) return i;
				}
			},
			refreshColorList() {
				this.isRefresh = false;
				this.isRefresh = true;
			},
			async onSave() {
				let res;
				this.$toast.loading(this);
				if(this.title == '修改商品信息') res = await this.$api.goodsManage.update(this.currentItem);	
				else res = await this.$api.goodsManage.add(this.currentItem);
				if(res.code == 200) {
					this.$toast.closeLoading(this);
					this.$toast.success(this,'保存成功',null,() => {
						if(this.title == '修改商品信息') uni.redirectTo({ url: `./goodsEdit?type=check&&goodsId=${ res.data }` })
						else uni.redirectTo({ url: './index' })
					});
				}else this.$toast.error(this,res.message);
				console.log('新增或修改的数据',this.currentItem)
			},
			initGoodsImage(url) {
				if(!url) return;
				this.fileList.splice(this.fileList.length - 1, 1, { status: 'success', message: '', url })
			}
		}
	}
</script>

<style lang="scss">
	.goods-content {
		// position: relative;
	}
	
	.goods-image {
		width: 160rpx;
		height: 160rpx;
	}
	
	.tag-box {
		display: flex;
		flex-wrap: wrap;
		.tag-item {
			margin-right: $spacing-small;
			margin-bottom: $spacing-small;
		}
	}
	
	.save-btn {
		z-index: 10;
		position: fixed;
		bottom: $spacing-large;
		left: 50%;
		transform: translateX(-50%);
	    width: 90%; 
	}
	
	.form-content {
		padding: 0 $spacing-base;
		padding-bottom: 120rpx;
	}
	
	.size-card {
		position: relative;
		display: flex;
		flex-direction: column;
		align-items: center;
		// background-color: #9dae8a;
		border: 2px solid #9dae8a;
		background-color: #fff;
		border-radius: 16px;
		box-shadow: 0 4px 12px 4px rgba(0,0,0,0.1);
		margin: $spacing-large 0;
		padding: $spacing-base;
		border-radius: 24rpx;
		.size-card-title {
			font-weight: bold;
			letter-spacing: 4rpx;
			// border: 2px solid gold;
		}
		.add-btn {
			position: absolute;
			right: $spacing-large;
			top: $spacing-small;
		}
		.color-table {
			width: 100%;
			// border: 2px solid salmon;
			.color-table-item {
				display: flex;
				justify-content: space-between;
				// border: 2px solid rebeccapurple;
				padding-top: $spacing-small;
				.color-table-item-box {
					display: flex;
					// border: 2px solid red;
					.color-table-item-box-title {
						font-size: $uni-font-size-paragraph;
						display: flex;
						align-items: center;
						padding-right: $spacing-small;
						// border: 2px solid goldenrod;
					}
					.color-table-item-box-content {
						display: flex;
						align-items: center;
						// border: 1px solid royalblue;
						.delete-btn {
							    height: 28px;
							    font-size: $uni-font-size-base;
							    display: flex;
							    align-items: center;
							    background-color: #dd524d;
								color: white;
						}
					}
				}
				
			}
		}
	}
	
</style>
